package com.zenithsun.news.news.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.syzg.common.config.SysProperties;
import com.syzg.common.controller.BaseController;
import com.syzg.common.exception.BaseException;
import com.syzg.common.model.WebInfo;
import com.syzg.common.model.WebObj;
import com.syzg.common.util.MethodUtil;
import com.syzg.common.util.PKCreator;
import com.syzg.common.util.SearchMap;
import com.syzg.core.page.PageResult;
import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;
import com.zenithsun.news.news.model.NewsInfo;
import com.zenithsun.news.news.service.NewsService;

@Controller
@RequestMapping("/path/news")
public class NewsController extends BaseController{
	
	@InitBinder
	 protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
	  {
	    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    CustomDateEditor editor = new CustomDateEditor(df, false);
	    binder.registerCustomEditor(Date.class, editor);
	  }
	
	static Logger log = LoggerFactory.getLogger(NewsController.class);
	
	@Resource
	private NewsService newsService;
	
	@RequestMapping("/listnews")
	public ModelAndView listnews(WebObj webObj)throws Exception{
		ModelAndView mv = new ModelAndView("/zenithsun/news/news/listnews.jsp");
		SearchMap searchMap = SearchMap.forClass(NewsInfo.class);
		searchMap.createAlias("newsColumns", "b");
		PageResult pageResult = newsService.findObjectsForPage(webObj.getPageNo(), SysProperties.PAGESIZE, searchMap);
        webObj.setPageResult(pageResult);
        mv.addObject("webObj",webObj);
        return mv;
	}
	
	@RequestMapping(value="/listnewsjson",produces="application/json;charset=UTF-8")
	public @ResponseBody String listnewsjson(String ncId,int pageNo) throws Exception {
		OutMessage outMessage=new OutMessage();
		try {
			SearchMap searchMap = SearchMap.forClass(NewsInfo.class);
			searchMap.createAlias("newsColumns", "b");
			searchMap.eq("b.id", ncId);
			PageResult pageResult = newsService.findObjectsForPage(pageNo, 1, searchMap);
			outMessage.setContent(pageResult);
			outMessage.setState(OutMessageState.Success);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent(e.getMessage());
		}
		return JSON.toJSONString(outMessage, SerializerFeature.WriteNullStringAsEmpty);
	}
	
	@RequestMapping("/initnewsCol_phone")
	public ModelAndView initnewsCol4Phone() throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/mobile/listnewsCol_phone.jsp");
		try {
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/initnews")
	public ModelAndView initnews() throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/news/addnews.jsp");
		try {
			mv.addObject("news", new NewsInfo());
			/*LoginObject loginObj = SystemUtil.getLoginObject();
			this.news.setCreatePersonId(new String(loginObj.getPersonId()));
			this.news.setCreator(loginObj.getPersonName());
			this.news.setCreateTime(new Date());*/
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/addnews")
	public @ResponseBody String addnews(NewsInfo news) throws Exception {
		WebObj webObj = new WebObj();
		try {
			/*LoginObject loginObj = SystemUtil.getLoginObject();
			this.news.setCreatePersonId(new String(loginObj.getPersonId()));
			this.news.setCreator(loginObj.getPersonName());
			this.news.setCreateTime(new Date());*/
			news.setId(PKCreator.getPk());
			news.setCreateTime(new Date());
			newsService.create(news);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add(e.getMessage());
		}
		return new JSONObject(webObj).toString();
	}
	
	@RequestMapping("/viewnews")
	public ModelAndView viewnews(NewsInfo news,ModelAndView mv) throws Exception {
		try {
			String id = news.getId();
			NewsInfo newsVO = newsService.findObjectById(id);
			if("pic".equals(newsVO.getType())){
				mv.setViewName("/zenithsun/news/news/viewnewsPic_phone.jsp");
			}else{
				mv.setViewName("/zenithsun/news/news/viewnewsPic_phone.jsp");
			}
			mv.addObject("news",newsVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/viewnewsphone")
	public ModelAndView viewnewsphone(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/news/viewnewsPic_phone.jsp");
		try {
			NewsInfo newsVO = newsService.findObjectById(id);
			if("pic".equals(newsVO.getType())){
				mv.setViewName("/zenithsun/news/news/viewnewsPic_phone.jsp");
			}else{
				mv.setViewName("/zenithsun/news/news/viewnewsText_phone.jsp");
			}
			mv.addObject("news",newsVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/editnews")
	public ModelAndView editnews(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/news/editnews.jsp");
		try {
			SearchMap searchMap = SearchMap.forClass(NewsInfo.class);
			searchMap.createAlias("newsColumns", "b");
			searchMap.eq("id", id);
			mv.addObject("news", newsService.findObjects(searchMap).get(0));
			WebObj webObj = new WebObj();
			mv.addObject("webObj",webObj);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/modnews")
	public @ResponseBody String modnews(String id,NewsInfo newsVO) throws Exception {
		WebObj webObj = new WebObj();
		try {
			NewsInfo news = newsService.findObjectById(id);
			news = (NewsInfo) MethodUtil.copyProperties(news, newsVO);
			newsService.update(news);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add(e.getMessage());
		}
		return new JSONObject(webObj).toString();
	}
	
	@RequestMapping("/delnews")
	public ModelAndView delnews(String id,WebObj webObj) throws Exception {
		String[] ids = webObj.getSelectedRow();
		try {
			if(ids == null) { //删除单个
				if(id == null) {
					ids = new String[0];
				} else {
					ids = new String[]{String.valueOf(id)};
				}
			}
			String[] idsStr = new String[ids.length];
			int i = 0;
			for(String idVO: ids) {
				idsStr[i++] = new String(idVO);
			}
			newsService.delete(idsStr);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return listnews(webObj);
	}
}
